<?php

namespace app\merchant\controller\proxy;

use app\merchant\controller\AuthController;
use app\merchant\model\agent\Ranking;
use app\merchant\model\proxy\Proxy as ProxyModel;
use app\merchant\model\user\User;
use app\merchant\model\wechat\WechatUser as UserModel;
use crmeb\basic\BaseModel;
use crmeb\services\{FormBuilder as Form, JsonService, UtilService as Util, UtilService};
use crmeb\services\upload\Upload;
use think\facade\Route as Url;


/**
 * 代理管理控制器
 * Class AgentManage
 * @package app\merchant\controller\agent
 */
class Proxy extends AuthController
{

    /**
     * 代理列表
     */
    public function index()
    {
        $this->assign('year', get_month());
        $this->assign('store_brokerage_statu', sys_config('store_brokerage_statu'));
        return $this->fetch();
    }
    /**
     * 代理设置
     */
    public function setting()
    {
        $mer_id = $this->adminId;
        ProxyModel::go_init($mer_id);
        $data = ProxyModel::get(['mer_id'=>$mer_id])->toArray();
        $this->assign(compact('data'));
        return $this->fetch();
    }

    /**
     * 代理列表
     */
    public function get_proxy_list()
    {
        $mer_id = $this->adminId;
        $where = Util::getMore([
            ['nickname', ''],
            ['sex', ''],
            ['excel', ''],
            ['subscribe', ''],
            ['order', ''],
            ['page', 1],
            ['limit', 20],
            ['user_type', ''],
            ['data', '']
        ]);
        $where['mer_id'] = $mer_id;
        return JsonService::successlayui(UserModel::proxySystemPage($where));
    }

    /**
     * 代理列表头部数据统计
     */
    public function get_badge()
    {
        $mer_id = $this->adminId;
        $where = Util::postMore([
            ['data', ''],
            ['nickname', ''],
            ['excel', ''],
        ]);
        $where['mer_id'] = $mer_id;
        return JsonService::successful(UserModel::getProxyBadge($where));
    }

    /**
     * 一级推荐人页面
     * @return mixed
     */
    public function stair($uid = '')
    {
        if ($uid == '') return $this->failed('参数错误');
        $this->assign('uid', $uid ?: 0);
        $this->assign('year', get_month());
        return $this->fetch();
    }


    /**
     * 代理订单页面
     */
    public function stair_order($uid = 0)
    {
        if ($uid == '') return $this->failed('参数错误');
        $this->assign('uid', $uid ?: 0);
        $this->assign('year', get_month());
        return $this->fetch();
    }

    /**
     * 统计推广订单列表
     */
    public function get_stair_order_list()
    {
        $where = Util::getMore([
            ['uid', $this->request->param('uid', 0)],
            ['data', ''],
            ['order_id', ''],
            ['type', ''],
            ['page', 1],
            ['limit', 20],
        ]);
        return JsonService::successlayui(UserModel::getProxyStairOrderList($where));
    }

    /**
     * 统计推广订单列表头部统计数据
     */
    public function get_stair_order_badge()
    {
        $where = Util::getMore([
            ['uid', ''],
            ['data', ''],
            ['order_id', ''],
            ['type', ''],
        ]);
        return JsonService::successful(UserModel::getStairOrderBadge($where));
    }

    /**
     * 代理会员列表
     */
    public function get_stair_list()
    {
        $where = Util::getMore([
            ['uid', $this->request->param('uid', 0)],
            ['data', ''],
            ['nickname', ''],
            ['type', ''],
            ['page', 1],
            ['limit', 20],
        ]);
        return JsonService::successlayui(UserModel::getProxyStairList($where));
    }

    public function get_stair_badge()
    {
        $where = Util::getMore([
            ['uid', ''],
            ['data', ''],
            ['nickname', ''],
            ['type', ''],
        ]);
        return JsonService::successful(UserModel::getSairBadge($where));
    }

    /**
     * 二级推荐人页面
     * @return mixed
     */
    public function stair_two($uid = '')
    {
        if ($uid == '') return $this->failed('参数错误');
        $spread_uid = User::where('spread_uid', $uid)->column('uid', 'uid');
        if (count($spread_uid))
            $spread_uid_two = User::where('spread_uid', 'in', $spread_uid)->column('uid', 'uid');
        else
            $spread_uid_two = [0];
        $list = User::alias('u')
            ->where('u.uid', 'in', $spread_uid_two)
            ->field('u.avatar,u.nickname,u.now_money,u.spread_time,u.uid')
            ->where('u.status', 1)
            ->order('u.add_time DESC')
            ->select()
            ->toArray();
        foreach ($list as $key => $value) $list[$key]['orderCount'] = StoreOrder::getOrderCount($value['uid']) ?: 0;
        $this->assign('list', $list);
        return $this->fetch('stair');
    }

    /*
     * 批量清除推广权限
     * */
    public function delete_promoter()
    {
        list($uids) = Util::postMore([
            ['uids', []]
        ], $this->request, true);
        if (!count($uids)) return JsonService::fail('请选择需要解除推广权限的用户！');
        User::beginTrans();
        try {
            if (User::where('uid', 'in', $uids)->update(['is_promoter' => 0])) {
                User::commitTrans();
                return JsonService::successful('解除成功');
            } else {
                User::rollbackTrans();
                return JsonService::fail('解除失败');
            }
        } catch (\PDOException $e) {
            User::rollbackTrans();
            return JsonService::fail('数据库操作错误', ['line' => $e->getLine(), 'message' => $e->getMessage()]);
        } catch (\Exception $e) {
            User::rollbackTrans();
            return JsonService::fail('系统错误', ['line' => $e->getLine(), 'message' => $e->getMessage()]);
        }

    }

    /*
     * 查看公众号推广二维码
     * @param int $uid
     * @return json
     * */
    public function look_code($uid = '', $action = '')
    {
        if (!$uid || !$action) return JsonService::fail('缺少参数');
        try {
            if (method_exists($this, $action)) {
                $res = $this->$action($uid);
                if ($res)
                    return JsonService::successful($res);
                else
                    return JsonService::fail(isset($res['msg']) ? $res['msg'] : '获取失败，请稍后再试！');
            } else
                return JsonService::fail('暂无此方法');
        } catch (\Exception $e) {
            return JsonService::fail('获取推广二维码失败，请检查您的微信配置', ['line' => $e->getLine(), 'messag' => $e->getMessage()]);
        }
    }

    /*
     * 获取小程序二维码
     * */
    public function routine_code($uid)
    {
        $userInfo = User::getUserInfos($uid);
        $name = $userInfo['uid'] . '_' . $userInfo['is_promoter'] . '_user.jpg';
        $imageInfo = SystemAttachment::getInfo($name, 'name');
        if (!$imageInfo) {
            $res = RoutineCode::getShareCode($uid, 'spread', '', '');
            if (!$res) throw new \think\Exception('二维码生成失败');
            $upload_type = sys_config('upload_type', 1);
            $upload = new Upload((int)$upload_type, [
                'accessKey' => sys_config('accessKey'),
                'secretKey' => sys_config('secretKey'),
                'uploadUrl' => sys_config('uploadUrl'),
                'storageName' => sys_config('storage_name'),
                'storageRegion' => sys_config('storage_region'),
            ]);
            $info = $upload->to('routine/spread/code')->validate()->stream($res['res'], $name);
            if ($info === false) {
                return $upload->getError();
            }
            $imageInfo = $upload->getUploadInfo();
            $imageInfo['image_type'] = $upload_type;
            SystemAttachment::attachmentAdd($imageInfo['name'], $imageInfo['size'], $imageInfo['type'], $imageInfo['dir'], $imageInfo['thumb_path'], 1, $imageInfo['image_type'], $imageInfo['time'], 2);
            RoutineQrcode::setRoutineQrcodeFind($res['id'], ['status' => 1, 'time' => time(), 'qrcode_url' => $imageInfo['dir']]);
            $urlCode = $imageInfo['dir'];
        } else $urlCode = $imageInfo['att_dir'];
        return ['code_src' => $urlCode];
    }

    /*
     * 获取公众号二维码
     * */
    public function wechant_code($uid)
    {
        $qr_code = QrcodeService::getForeverQrcode('spread', $uid);
        if (isset($qr_code['url']))
            return ['code_src' => $qr_code['url']];
        else
            throw new \think\Exception('获取失败，请稍后再试！');
    }

    /**
     * TODO 查看小程序推广二维码
     * @param string $uid
     */
    public function look_xcx_code($uid = '')
    {
        if (!strlen(trim($uid))) return JsonService::fail('缺少参数');
        try {
            $userInfo = User::getUserInfos($uid);
            $name = $userInfo['uid'] . '_' . $userInfo['is_promoter'] . '_user.jpg';
            $imageInfo = SystemAttachment::getInfo($name, 'name');
            if (!$imageInfo) {
                $res = RoutineCode::getShareCode($uid, 'spread', '', '');
                if (!$res) return JsonService::fail('二维码生成失败');
                $upload_type = sys_config('upload_type', 1);
                $upload = new Upload((int)$upload_type, [
                    'accessKey' => sys_config('accessKey'),
                    'secretKey' => sys_config('secretKey'),
                    'uploadUrl' => sys_config('uploadUrl'),
                    'storageName' => sys_config('storage_name'),
                    'storageRegion' => sys_config('storage_region'),
                ]);
                $info = $upload->to('routine/spread/code')->validate()->stream($res['res'], $name);
                if ($info === false) {
                    return $upload->getError();
                }
                $imageInfo = $upload->getUploadInfo();
                $imageInfo['image_type'] = $upload_type;
                SystemAttachment::attachmentAdd($imageInfo['name'], $imageInfo['size'], $imageInfo['type'], $imageInfo['dir'], $imageInfo['thumb_path'], 1, $imageInfo['image_type'], $imageInfo['time'], 2);
                RoutineQrcode::setRoutineQrcodeFind($res['id'], ['status' => 1, 'time' => time(), 'qrcode_url' => $imageInfo['dir']]);
                $urlCode = $imageInfo['dir'];
            } else $urlCode = $imageInfo['att_dir'];
            return JsonService::successful(['code_src' => $urlCode]);
        } catch (\Exception $e) {
            return JsonService::fail('查看推广二维码失败！', ['line' => $e->getLine(), 'meassge' => $e->getMessage()]);
        }
    }

    /*
     * 解除单个用户的推广权限
     * @param int $uid
     * */
    public function delete_spread($uid = 0)
    {
        if (!$uid) return JsonService::fail('缺少参数');
        if (User::where('uid', $uid)->update(['is_promoter' => 0]))
            return JsonService::successful('解除成功');
        else
            return JsonService::fail('解除失败');
    }

    /*
     * 清除推广人
     * */
    public function empty_spread($uid = 0)
    {
        if (!$uid) return JsonService::fail('缺少参数');
        $res = User::where('uid', $uid)->update(['spread_uid' => 0]);
        if ($res)
            return JsonService::successful('清除成功');
        else
            return JsonService::fail('清除失败');
    }

    /**
     * 个人资金详情页面
     * @return mixed
     */
    public function now_money($uid = '')
    {
        if ($uid == '') return $this->failed('参数错误');
        $list = UserBill::where('uid', $uid)->where('category', 'now_money')
            ->field('mark,pm,number,add_time')
            ->where('status', 1)->order('add_time DESC')->select()->toArray();
        foreach ($list as &$v) {
            $v['add_time'] = $v['add_time'] ? date('Y-m-d H:i:s', $v['add_time']) : '';
        }
        $this->assign('list', $list);
        return $this->fetch();
    }


    /**
     * 保存代理数据2
     */
    public function save_data_two(){
        $mer_id  = $this->adminId;
        $data     = Util::postMore([
            'one_name','two_name','three_name',
            'one_percent','two_percent','three_percent',
            'one_recharge','two_recharge','three_recharge',
            'one_buy','two_buy','three_buy','is_open','proxy_way',
            'one_goods','two_goods','three_goods'
        ]);
        $where['mer_id'] = $mer_id;
        $result = ProxyModel::update($data,$where);
        if($result){
            return JsonService::successful('操作成功');
        }else{
            return JsonService::successful('操作失败');
        }

    }

    /*************代理设置***********/

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function user_index()
    {
        return $this->fetch();
    }

    /**
     * 获取user表
     *
     * @return json
     */
    public function get_user_list()
    {
        $mer_id = $this->adminId;
        $where = Util::getMore([
            ['page', 1],
            ['limit', 20],
            ['nickname', ''],
            ['status', ''],
            ['pay_count', ''],
            ['is_promoter', ''],
            ['order', ''],
            ['data', ''],
            ['user_type', ''],
            ['country', ''],
            ['province', ''],
            ['city', ''],
            ['user_time_type', ''],
            ['user_time', ''],
            ['sex', ''],
            ['level', ''],
            ['group_id', ''],
        ]);
        $where['mer_id'] = $mer_id;
        return JsonService::successlayui(User::getUserList($where));
    }

    /**
     * 编辑模板消息
     * @param $id
     * @return mixed|\think\response\Json|void
     */
    public function edit($uid)
    {
        if (!$uid)  return JsonService::fail('数据不存在!');
        $user = User::get($uid);
        if (!$user) return JsonService::fail('数据不存在!');
        $f = array();
        $f[] = Form::input('uid', '用户编号', $user->getData('uid'))->disabled(1);
        $f[] = Form::radio('proxy_level', '代理等级', $user->getData('proxy_level'))->options([['value' => 1, 'label' => '一级代理'], ['value' => 2, 'label' => '二级代理'], ['value' => 3, 'label' => '三级代理'], ['value' => 0, 'label' => '会员']]);
        $form = Form::make_post_form('添加用户通知', $f, Url::buildUrl('update', array('uid' => $uid)), 5);
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    /**
     * @param $uid
     */
    public function update($uid)
    {
        $data = Util::postMore([
            ['proxy_level', 0],
        ]);
        if (!$uid) return $this->failed('数据不存在');
        $user = User::get($uid);
        if (!$user) return JsonService::fail('数据不存在!');
        BaseModel::beginTrans();
        $res1 = true;
        $res2 = true;
        $edit = array();
        $edit['proxy_level'] = $data['proxy_level'];
        if ($edit) $res3 = User::edit($edit, $uid);
        else $res3 = true;
        $old_proxy_level = $user['proxy_level'];
        if($old_proxy_level!=$data['proxy_level']) { //提交等级与原来等级不同
            if ($data['proxy_level'] > 0) {
                //修改代理等级，则该代理下面会员的相应代理也修改
                $old_proxy_level = $user['proxy_level'];
                //1先清空相应的代理等级
                if ($old_proxy_level == 1) {
                    $maps1['level_one_uid'] = $uid;
                    $ups1['level_one_uid'] = 0;
                    $change_uid1 = User::where($maps1)->column('uid');
                    User::update($ups1, $maps1);
                } elseif ($old_proxy_level == 2) {
                    $maps2['level_two_uid'] = $uid;
                    $ups2['level_two_uid'] = 0;
                    $change_uid2 = User::where($maps2)->column('uid');
                    User::update($ups2, $maps2);
                } elseif ($old_proxy_level == 3) {
                    $maps3['level_three_uid'] = $uid;
                    $ups3['level_three_uid'] = 0;
                    $change_uid3 = User::where($maps3)->column('uid');
                    User::update($ups3, $maps3);
                }
                //2再修改等级
                if ($data['proxy_level'] == 1) {
                    $maps11[] = ['uid', 'in', $change_uid1];
                    $ups1['level_one_uid'] = $uid;
                    User::update($ups1, $maps11);
                } elseif ($old_proxy_level == 2) {
                    $maps22[] = ['uid', 'in', $change_uid2];
                    $ups2['level_two_uid'] = $uid;
                    User::update($ups2, $maps2);
                } elseif ($old_proxy_level == 3) {
                    $maps33[] = ['uid', 'in', $change_uid3];
                    $ups2['level_three_uid'] = $uid;
                    User::update($ups3, $maps3);
                }
            }
        }
        if ($res1 && $res2 && $res3) $res = true;
        else $res = false;
        BaseModel::checkTrans($res);
        if ($res) return JsonService::successful('修改成功!');
        else return JsonService::fail('修改失败');
    }

    /****************排名设置****************/

    public function rank_index($type=2,$way=1,$rank_time=1){
        $this->assign(compact('type','way','rank_time'));
        return $this->fetch();
    }


    /**
     * 获取排行列表
     */
    public function get_rank_list()
    {
        $mer_id = $this->adminId;
        $where = Util::getMore([
            ['page', 1],
            ['limit', 20],
            ['type', 2],
            ['rank_time', 1],
        ]);
        $where['mer_id'] = $mer_id;
        return JsonService::successlayui(Ranking::getUserList($where));
    }

    /**
    * 创建form表单
    */
    public function create($id = 0)
    {
        if ($id) $vipinfo = Ranking::get($id);
        $field[] = Form::input('nickname', '会员昵称', isset($vipinfo) ? $vipinfo->nickname : '')->col(Form::col(24));
        $field[] = Form::frameImageOne('avatar', '头像', Url::buildUrl('merchant/widget.images/index', array('fodder' => 'avatar')), isset($vipinfo) ? $vipinfo->avatar : '')->icon('image')->width('100%')->height('500px');
        $field[] = Form::number('count', '团队人数', isset($vipinfo) ? $vipinfo->count : 0)->min(0)->col(24);
        $field[] = Form::number('brokerage_price', '团队佣金', isset($vipinfo) ? $vipinfo->brokerage_price : 0)->min(0)->col(24);
        $field[] = Form::radio('rank_time', '月/周', isset($vipinfo) ? $vipinfo->rank_time : 1)->options([['label' => '周排行', 'value' => 1], ['label' => '月排行', 'value' => 2]])->col(8);
        $form = Form::make_post_form('添加代理排行', $field, Url::buildUrl('save', ['id' => $id]), 2);
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }


    /**
     * 会员等级添加或者修改
     */
    public function save($id = 0)
    {
        $mer_id = $this->adminId;
        $data = UtilService::postMore([
            ['nickname', ''],
            ['avatar', ''],
            ['count', 0],
            ['brokerage_price', 0],
            ['rank_time', 1],
        ]);
        if (!$data['nickname']) return JsonService::fail('请输入会员昵称');
        if (!$data['avatar']) return JsonService::fail('请选择会员头像');
        if (!$data['count']) return JsonService::fail('请输入会员团队人数');
        if (!$data['brokerage_price']) return JsonService::fail('请输入团队佣金');
        Ranking::beginTrans();
        try {
            //修改
            if ($id) {
                if (Ranking::edit($data, $id)) {
                    Ranking::commitTrans();
                    return JsonService::successful('修改成功');
                } else {
                    Ranking::rollbackTrans();
                    return JsonService::fail('修改失败');
                }
            } else {
                //新增
                $data['mer_id']  = $mer_id;
                $data['type']    = 2;
                if (Ranking::create($data)) {
                    Ranking::commitTrans();
                    return JsonService::successful('添加成功');
                } else {
                    Ranking::rollbackTrans();
                    return JsonService::fail('添加失败');
                }
            }
        } catch (\Exception $e) {
            Ranking::rollbackTrans();
            return JsonService::fail($e->getMessage());
        }
    }


    /**
      * 删除会员等级
      */
    public function delete($id = 0)
    {
        if (Ranking::destroy(['id'=>$id]))
            return JsonService::successful('删除成功');
        else
            return JsonService::fail('删除失败');
    }

}
